package com.ruoyi.loan.except;

import com.ruoyi.common.core.web.domain.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOException;

/**
 * @author 项目全局异常处理
 * @description TODO
 * @date 2022/11/29 20:46
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /** JSR303后端验证异常处理 */
	 @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult handleError(MethodArgumentNotValidException e){
        log.warn("Method Argument Not Valid",e);
        BindingResult bindingResult = e.getBindingResult();
        FieldError fieldError = bindingResult.getFieldError();
        String message = String.format("%s",fieldError.getDefaultMessage());
        return AjaxResult.error(500,"JSR303后端验证异常");
    }
    /** 空指针异常 */
    @ExceptionHandler(value = NullPointerException.class)
    public AjaxResult nullPointerExceptionHandler(NullPointerException ex) {
        ex.printStackTrace();
        return AjaxResult.error("500","空指针异常NullPointerException");
    }

    /** 类型转换异常 */
    @ExceptionHandler(ClassCastException.class)
    public AjaxResult classCastExceptionHandler(ClassCastException ex) {
        ex.printStackTrace();
        return AjaxResult.error("500","类型转换异常ClassCastException");
    }

    /** IO异常 */
    @ExceptionHandler(IOException.class)
    public AjaxResult iOExceptionHandler(IOException ex) {
        ex.printStackTrace();
        return AjaxResult.error("500","IO异常IOException");
    }
    /** 通用异常  */
    @ExceptionHandler(Exception.class)
    public AjaxResult ExceptionHandler(Exception ex) {
        ex.printStackTrace();
        return AjaxResult.error("500","通用异常Exception"+ex.getMessage());
    }
}
